package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shop/models"
)

type GoodsController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *GoodsController) Get() {

}
func (c *GoodsController) Add() {
	name := c.GetString("name")
	price, _ := c.GetInt("price")
	fl := c.GetString("fl")
	img := c.GetString("img")
	zt := c.GetString("zt")
	goods := models.Goods{
		Name:  name,
		Price: price,
		Fl:    fl,
		Img:   img,
		Zt:    zt,
	}
	err := models.DB.Create(&goods).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: goods,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c GoodsController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Goods{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}

}
func (c GoodsController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Goods{}).Count(&count)
	offest := (page - 1) * size
	var allgoods []models.Goods
	err := models.DB.Model(&models.Goods{}).Offset(offest).Limit(size).Find(&allgoods).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: allgoods,
		}
		c.ServeJSON()
	}
}
